import React, { useState, useEffect } from 'react'
import Taro, { useDidShow } from '@tarojs/taro'
import { View } from '@tarojs/components'
import cls from 'classnames';

import './index.scss'

export interface TabProps {
    title: string,
    name?: string,
}

export interface TabsProps {
    active?: string | number,
    children: any,
    customClass: string,
    onChange?: (index: number, name: string) => void
}

export const Tabs: React.FC<TabsProps> = ({
    children, active, onChange, customClass
}) => {
    const tabs = children.map(it => it.props.title);
    const names = children.map(it => it.props.name).filter(it => it);
    let currIndex = active || 0;
    if (names.length === tabs.length) {
        currIndex = names.findIndex(it => it === active);
    }

    let [current, setCurrent] = useState<number | string>(currIndex);
    const [lineStyle, setLineStyle] = useState({});

    const currentTab = children.find((child: any, index: number) => index === current);

    // 设置下划线位置
    const setLine = (index) => {
        const query = Taro.createSelectorQuery();
        query.select('.xxm-tab').boundingClientRect((rects) => {
            const left = rects.width * index + rects.width / 2;
            const line = {
                transform: `translateX(${left}px) translateX(-50%)`,
                display: 'block'
            };
            setLineStyle(line);
        }).exec();
    }

    useEffect(() => {
        // 默认设置
        setTimeout(() => {
            setLine(current);
        }, 100);
    }, [])

    return (
        <View
            className={cls(
                'xxm-tabs',
                customClass || '',
            )}
        >
            <View
                className="xxm-tabs__wrap"
            >
                <View
                    className="xxm-tabs__nav xxm-tabs__nav--line"
                >
                    {
                        tabs.map((tab, index) => (
                            <View
                                key={index}
                                className={cls('xxm-tab', {
                                    'xxm-tab__active': current === index
                                })}
                                onClick={() => {
                                    setCurrent(index);
                                    setLine(index);
                                    onChange && onChange(index, names[index] || '');
                                }}
                            >{tab}</View>
                        ))
                    }
                    <View
                        className="xxm-tabs__line"
                        style={lineStyle}
                    ></View>
                </View>
            </View>
            {currentTab}
        </View>
    )
}
